<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * Created on 2012-7-7
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 class articles_m extends CI_Model{
 	const TB_ARTICLE = 'articles';
 	const TB_USER = 'users';
 	function __construct(){
 		parent::__construct();
 	}
 	/*
 	 * 根据分类返回数据
 	 * @return array();
 	 */
 	function get_by_page($type,$author,$offset,$limit){
 		$where ='';
 		$category_tree = common::_get_where_from('category_tree',array('alias'=>$type),'category')->result();
 		$tree = $category_tree[0]->category_tree."_%";
		$this->db->select('articles.*,users.username,category.*');
		if($author!=''){
			if($type != 'all'){
				$where ="alias = '$type' and username = '$author' or username = '$author' and category_tree like '$tree'";
			}else{
				$where ="username = '$author'";
			}
		}else{
			if($type != 'all'){
				$where ="alias = '$type' or category_tree like '$tree'";
			}
		}
		if(!empty($where)){
			$this->db->where($where);
		}
		$this->db->from(self::TB_ARTICLE);
		$this->db->join('users','articles.author_id = users.userid','left');
		$this->db->join('category','articles.category_id = category.cid','left');
		$this->db->limit($limit,$offset);
		$data =$this->db->get();
		return $data;
 	}

/* 根据分类获取文章数量
 	 *
 	 */
 	function get_count_by_page($type,$author){
 		$category_tree = common::_get_where_from('category_tree',array('alias'=>$type),'category')->result();
 		$tree = $category_tree[0]->category_tree."_%";

 		if($type != 'all')
 		{
 			$where = "alias = '$type' or category_tree like '$tree'";
	 		$type_id = $this->db->select('cid')
	 							->from('category')
	 							->where($where)
	 							->get()
	 							->result_array();
	 		foreach($type_id as $id){
	 			$ids[]=$id['cid'];
	 		}

 		}
 		if($author!=''){
			$author_id = common::_get_id_by_username($author);
			$author_id = $author_id[0]->userid;
			$this->db->where(array('author_id'=>$author_id));
 		}

		$this->db->select('count(*) as count');
		$this->db->from(self::TB_ARTICLE);
		if(isset($ids)){
			$this->db->where_in('category_id',$ids);
		}
		$count =$this->db->get()->result();

 		return $count[0]->count;

 	}

 /*
  * 根据文章id返回文章信息。
  */
 	function get_article_by_id($id){
		$this->db->select('articles.*,users.username,category.*');
		$this->db->where(array('articles.id'=>$id));
		$this->db->from(self::TB_ARTICLE);
		$this->db->join('users','articles.author_id = users.userid','left');
		$this->db->join('category','articles.category_id = category.cid','left');
		$data =$this->db->get();
		return $data;
 	}
 /*
  * 根据作者id返回文章信息。
  */

 }
?>
